//
//  AnalysisListViewController.m
//  金融
//
//  Created by Apple on 2017/12/28.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "AnalysisListViewController.h"
#import "AnalysisCell.h"
#import "HomeModel.h"
#import "HomeWebViewController.h"

static NSString * cellID = @"AnalysisCell";
@interface AnalysisListViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView    * tableView;
@property (nonatomic, strong) NSMutableArray * dataArray;
@property (nonatomic, assign) NSInteger         page;
@property (nonatomic, assign) BOOL              hasMore;
@end

@implementation AnalysisListViewController

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"AnalysisCell" bundle:nil] forCellReuseIdentifier:cellID];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    }
    return _tableView;
}
- (void)footerRefresh
{
    if (self.hasMore) {
        self.page ++;
        [self networking];
    }
}
- (void)networking
{
    WeakSelf
    NSDictionary * dict = @{@"page":[NSNumber numberWithInteger:self.page],@"size":[NSNumber numberWithInteger:10],@"data":@{@"searchTypeId":self.value}};
    [HttpRequest postWithURLString:HOST(@"app/analysis/list") parameters:dict showProgressHud:YES success:^(NSDictionary * _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == CODESUCCESS) {
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.dataArray addObjectsFromArray:responseObject[@"data"][@"content"]];
            if (weakSelf.page >= [responseObject[@"data"][@"totalPages"] integerValue] ) {
                weakSelf.hasMore = NO;
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                weakSelf.tableView.mj_footer.hidden = YES;
                weakSelf.tableView.mj_footer.state = MJRefreshStateNoMoreData;
            }
            if (weakSelf.dataArray.count > 0) {
                weakSelf.tableView.hidden = NO;
                weakSelf.NoDataView.hidden = YES;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.tableView reloadData];
                });
            }else{
                weakSelf.tableView.hidden = YES;
                weakSelf.NoDataView.hidden = NO;
            }
        }
        [weakSelf.tableView.mj_footer endRefreshing];
    } failure:^(NSError * _Nullable error) {
        weakSelf.tableView.hidden = YES;
        weakSelf.NoDataView.hidden = NO;
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        weakSelf.tableView.mj_footer.hidden = YES;
    }login:^(BOOL isLogin) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf ShowLoginView];
        });
    }];
}
- (void)ShowLoginView
{
    HFLoginView * logView = [HFLoginView shareInit];
    [logView show];
    WeakSelf
    logView.clickPushBlock = ^(NSInteger index) {
        if (index == 0) {
            [weakSelf PushRigest];
        }else{
            [weakSelf PushLogin];
        }
    };
}
- (void)PushRigest
{
    RegisterViewController * rc = [[RegisterViewController alloc] init];
    rc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:rc animated:YES];
}
- (void)PushLogin
{
    LoginViewController * lgvc = [[LoginViewController alloc] init];
    lgvc.myClass = NSStringFromClass([self class]);
    WeakSelf
    lgvc.LoginSuccessBlock = ^{
        [weakSelf reloadCusData];
    };
    lgvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:lgvc animated:YES];
}
- (void)reloadCusData
{
    [self.dataArray removeAllObjects];
    self.page = 1;
    self.hasMore = YES;
    [self networking];
}
- (void)setNavBar
{
    [self.barView addSubview:self.titleL];
    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.barView);
        make.width.mas_greaterThanOrEqualTo(10);
        make.height.mas_greaterThanOrEqualTo(10);
    }];
    self.titleL.text = self.cusTitle;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavBar];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.barView.mas_bottom);
        if (@available(iOS 11.0, *)) {
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        }else{
            make.bottom.mas_equalTo(self.view.mas_bottom);
        }
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(reloadCusData)];
    [self reloadCusData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AnalysisCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    [cell setDataWithModel:self.dataArray[indexPath.row]];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 105.f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary * dict = self.dataArray[indexPath.row];
    HomeWebViewController * hc = [[HomeWebViewController alloc] init];
    hc.cusTitle = dict[@"title"];
    hc.imageUrl = dict[@"mainImg"][@"path"];
    hc.shareUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@?id=%@",OS,@"/wap/app/analysis/info",dict[@"id"]]];
    hc.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@?token=%@&id=%@&pc=1",OS,@"/wap/app/analysis/info",[HFUser getSaveToken],dict[@"id"]]];
    hc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:hc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
